<template>
  <div class="house-manage">
    <div class="page-header">
      <h2>房源管理</h2>
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd">发布房源</el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-box">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="房源标题">
          <el-input v-model="searchForm.title" placeholder="请输入房源标题" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="待审核" value="0"></el-option>
            <el-option label="已上架" value="1"></el-option>
            <el-option label="已下架" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <el-table :data="tableData" border stripe v-loading="loading">
      <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
      <el-table-column prop="title" label="房源标题" min-width="200"></el-table-column>
      <el-table-column prop="address" label="地址" min-width="200"></el-table-column>
      <el-table-column prop="price" label="月租金（元）" width="120" align="right"></el-table-column>
      <el-table-column prop="area" label="面积（㎡）" width="100" align="right"></el-table-column>
      <el-table-column prop="roomType" label="户型" width="100"></el-table-column>
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 0" type="warning">待审核</el-tag>
          <el-tag v-else-if="scope.row.status === 1" type="success">已上架</el-tag>
          <el-tag v-else-if="scope.row.status === 2" type="info">已下架</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="viewCount" label="浏览量" width="100" align="right"></el-table-column>
      <el-table-column prop="createTime" label="发布时间" width="160"></el-table-column>
      <el-table-column label="操作" width="200" fixed="right" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" style="color: #f56c6c;">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-box">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNo"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="60%" :close-on-click-modal="false">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="房源标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入房源标题"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入详细地址"></el-input>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="月租金" prop="price">
              <el-input v-model.number="form.price" placeholder="请输入月租金">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="面积" prop="area">
              <el-input v-model.number="form.area" placeholder="请输入面积">
                <template slot="append">㎡</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="户型" prop="roomType">
              <el-select v-model="form.roomType" placeholder="请选择户型">
                <el-option label="一室一厅" value="一室一厅"></el-option>
                <el-option label="两室一厅" value="两室一厅"></el-option>
                <el-option label="三室两厅" value="三室两厅"></el-option>
                <el-option label="四室两厅" value="四室两厅"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="朝向" prop="orientation">
              <el-select v-model="form.orientation" placeholder="请选择朝向">
                <el-option label="南" value="南"></el-option>
                <el-option label="北" value="北"></el-option>
                <el-option label="东" value="东"></el-option>
                <el-option label="西" value="西"></el-option>
                <el-option label="南北" value="南北"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="楼层">
              <el-input v-model.number="form.floor" placeholder="请输入楼层">
                <template slot="append">层</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总楼层">
              <el-input v-model.number="form.totalFloor" placeholder="请输入总楼层">
                <template slot="append">层</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="装修情况">
              <el-select v-model="form.decoration" placeholder="请选择装修情况">
                <el-option label="毛坯" value="毛坯"></el-option>
                <el-option label="简装" value="简装"></el-option>
                <el-option label="精装" value="精装"></el-option>
                <el-option label="豪华" value="豪华"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="房源描述">
          <el-input type="textarea" v-model="form.description" :rows="4" placeholder="请输入房源描述"></el-input>
        </el-form-item>
        <el-form-item label="配套设施">
          <el-checkbox-group v-model="form.facilities">
            <el-checkbox label="空调"></el-checkbox>
            <el-checkbox label="洗衣机"></el-checkbox>
            <el-checkbox label="冰箱"></el-checkbox>
            <el-checkbox label="热水器"></el-checkbox>
            <el-checkbox label="床"></el-checkbox>
            <el-checkbox label="衣柜"></el-checkbox>
            <el-checkbox label="WiFi"></el-checkbox>
            <el-checkbox label="燃气"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="房源图片">
          <el-upload
            :action="uploadUrl"
            :headers="uploadHeaders"
            list-type="picture-card"
            :on-success="handleUploadSuccess"
            :on-remove="handleRemove"
            :file-list="fileList"
            :limit="9"
            accept="image/*">
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">支持jpg、png格式，单张最大5MB，最多9张</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'HouseManage',
  data() {
    return {
      loading: false,
      searchForm: {
        title: '',
        status: ''
      },
      tableData: [],
      pageNo: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: '添加房源',
      form: {
        id: null,
        title: '',
        address: '',
        price: null,
        area: null,
        roomType: '',
        orientation: '',
        floor: null,
        totalFloor: null,
        decoration: '',
        description: '',
        facilities: [],
        picList: []
      },
      fileList: [],
      uploadUrl: '',
      uploadHeaders: {},
      rules: {
        title: [{ required: true, message: '请输入房源标题', trigger: 'blur' }],
        address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
        price: [{ required: true, message: '请输入月租金', trigger: 'blur' }],
        area: [{ required: true, message: '请输入面积', trigger: 'blur' }],
        roomType: [{ required: true, message: '请选择户型', trigger: 'change' }]
      }
    }
  },
  created() {
    this.loadData()
    this.uploadUrl = this.$config ? (this.$config.baseUrl + '/api/house/uploadPic') : 'http://localhost:8885/rent/api/house/uploadPic'
    const token = localStorage.getItem('token')
    if (token) {
      this.uploadHeaders = { token }
    }
  },
  methods: {
    loadData() {
      this.loading = true
      const params = {
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        keyword: this.searchForm.title || undefined  // 使用keyword进行搜索
      }

      // 调用API获取房源列表
      this.$network.pendingHouseList(params).then(res => {
        if (res.data.code === 200) {
          this.tableData = res.data.data.records || []
          console.log(res.data.data);

          this.total = res.data.data.total || 0
        } else {
          this.$message.error(res.data.message || '获取房源列表失败')
        }
      }).catch(error => {
        console.error('获取房源列表失败:', error)
        this.$message.error('获取房源列表失败')
      }).finally(() => {
        this.loading = false
      })
    },
    handleSearch() {
      this.pageNo = 1
      this.loadData()
    },
    handleReset() {
      this.searchForm = {
        title: '',
        status: ''
      }
      this.pageNo = 1
      this.loadData()
    },
    handleAdd() {
      this.dialogTitle = '发布房源'
      this.dialogVisible = true
      this.form = {
        id: null,
        title: '',
        address: '',
        price: null,
        area: null,
        roomType: '',
        orientation: '',
        floor: null,
        totalFloor: null,
        decoration: '',
        description: '',
        facilities: [],
        picList: []
      }
      this.fileList = []
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.clearValidate()
      })
    },
    handleEdit(row) {
      this.dialogTitle = '编辑房源'
      this.dialogVisible = true
      this.form = { ...row }

      // 处理facilities字段，如果是字符串则转为数组
      if (typeof this.form.facilities === 'string') {
        try {
          this.form.facilities = JSON.parse(this.form.facilities)
        } catch (e) {
          this.form.facilities = []
        }
      }

      // 处理图片列表
      if (row.picList && Array.isArray(row.picList)) {
        this.fileList = row.picList.map(pic => ({
          name: pic.url,
          url: pic.url
        }))
        this.form.picList = row.picList.map(pic => pic.url)
      } else {
        this.fileList = []
        this.form.picList = []
      }
    },
    handleView(row) {
      // 获取房源详情
      this.$network.getHouseDetail(row.id).then(res => {
        if (res.data.code === 200) {
          // 可以打开一个详情对话框显示房源详情
          this.$message.success('获取详情成功')
          console.log('房源详情:', res.data.data)
          // TODO: 可以增加详情对话框
        } else {
          this.$message.error(res.data.message || '获取详情失败')
        }
      }).catch(error => {
        console.error('获取详情失败:', error)
        this.$message.error('获取详情失败')
      })
    },
    handleDelete(row) {
      this.$confirm('确定要删除该房源吗？删除后无法恢复', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用删除API
        this.$network.deleteHouseById(row.id).then(res => {
          if (res.data.code === 200) {
            this.$message.success('删除成功')
            this.loadData()
          } else {
            this.$message.error(res.data.message || '删除失败')
          }
        }).catch(error => {
          console.error('删除房源失败:', error)
          this.$message.error('删除失败')
        })
      }).catch(() => {
        // 取消删除
      })
    },
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const apiMethod = this.form.id ? this.$network.updateHouse : this.$network.publishHouse
          const successMsg = this.form.id ? '更新成功' : '发布成功，等待审核'

          apiMethod(this.form).then(res => {
            if (res.data.code === 200) {
              this.$message.success(successMsg)
              this.dialogVisible = false
              this.loadData()
            } else {
              this.$message.error(res.data.message || '操作失败')
            }
          }).catch(error => {
            console.error('提交失败:', error)
            this.$message.error('提交失败')
          })
        }
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.loadData()
    },
    handleCurrentChange(val) {
      this.pageNo = val
      this.loadData()
    },
    handleUploadSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.$message.success('图片上传成功')
        // 将图片URL添加到表单的picList中
        if (!this.form.picList) {
          this.form.picList = []
        }
        this.form.picList.push(response.data)
      } else {
        this.$message.error(response.message || '图片上传失败')
        // 移除上传失败的文件
        const index = fileList.indexOf(file)
        if (index > -1) {
          fileList.splice(index, 1)
        }
      }
    },
    handleRemove(file, fileList) {
      // 从picList中移除对应的URL
      if (this.form.picList) {
        const url = file.response ? file.response.data : file.url
        const index = this.form.picList.indexOf(url)
        if (index > -1) {
          this.form.picList.splice(index, 1)
        }
      }
    }
  }
}
</script>

<style scoped>
.house-manage {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
}

.search-box {
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-form {
  margin: 0;
}

.pagination-box {
  margin-top: 20px;
  text-align: right;
}
</style>

